//
//  UserInfoTableViewController.m
//  ITHome
//
//  Created by lanou3g on 15/7/14.
//  Copyright (c) 2015年 YAX. All rights reserved.
//  
#import "UserInfoTableViewController.h"
#import "UserAvatarTableViewCell.h"
#import "MyHomeTableViewCell.h"
#import "NameViewController.h" //姓名
#import "IntroductionViewController.h" //一句话简介
#import "CityData.h"
#import "UserInfoModel.h"
#import "UIImage+CornerImage.h"

@interface UserInfoTableViewController ()<UIPickerViewDataSource, UIPickerViewDelegate,NameProtocol, UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) NSMutableArray *cityDataArray; // 城市数组
@property (nonatomic, strong) UIView *shadowView; //视图
@property (nonatomic, strong) UIPickerView *pickerView; // pickerView
@property (nonatomic, strong) UIButton *cancelBtn; // 取消按钮
@property (nonatomic, strong) UIButton *confirmBtn; //确定按钮
@property (nonatomic, strong) NSString *locationString; // 保存当前选中的所在地

@property(nonatomic, retain)UIImageView *avatarImageView; // 头像



@end

@implementation UserInfoTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self loadNavigationIndfo];
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style: UITableViewStyleGrouped];
    // 获取城市数据
    self.cityDataArray = [CityData cityData];

}


#pragma mark - 设置导航栏
- (void)loadNavigationIndfo
{
    self.navigationController.navigationBar.barTintColor = [UIColor RGBColor:71 green:128 blue:208 alpha:1];
    
    self.navigationItem.title = @"个人中心";
    // 取消
    UIBarButtonItem *leftBackButton = [UIBarButtonItem itemWithTarget:self Action:@selector(backAction) title:@"取消"];
    self.navigationItem.leftBarButtonItem = leftBackButton;
    
    // 保存
    UIBarButtonItem *rightSaveButton  = [UIBarButtonItem itemWithTarget:self Action:@selector(saveAction) title:@"保存"];
    self.navigationItem.rightBarButtonItem = rightSaveButton;
    
    // 标题
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
}

#pragma mark - 返回按钮触发事件
- (void)backAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 保存按钮触发事件
- (void)saveAction
{
    // 从数据库取出数据
    NSMutableArray *userInfoArray = [FMDBManage selectAllUserInfo];
    UserInfoModel *userInfoModel = [userInfoArray objectAtIndex:0];
    
    // 判断所在地是否为空
    if (self.locationString != nil)
    {
        // 分割字符串
        NSArray *locationArray = [self.locationString componentsSeparatedByString:@" "];
        // 修改数据
        BOOL flag = [FMDBManage updateUserInfoWithOpenId:userInfoModel.openId city:locationArray[1] province:locationArray[0] figureurl_qq_2:self.userInfoModel.figureurl_qq_2 nickname:self.userInfoModel.nickname indirect:self.userInfoModel.indirect];
        if (flag)
        {
            // 创建一个通知··用户退出状态的通知 让相关页面刷新数据
            [[NSNotificationCenter defaultCenter] postNotificationName:kUpdateUserInfoSuccessed object:self];
            
            // 回到上一个界面
            [self backAction];
        }
        else
        {
            // 什么都不做
        }
    }
    else
    {
        // 修改数据
        BOOL flag = [FMDBManage updateUserInfoWithOpenId:userInfoModel.openId city:userInfoModel.city province:userInfoModel.province figureurl_qq_2:self.userInfoModel.figureurl_qq_2 nickname:self.userInfoModel.nickname indirect:self.userInfoModel.indirect];
        if (flag)
        {
            // 创建一个通知··用户退出状态的通知 让相关页面刷新数据
            [[NSNotificationCenter defaultCenter] postNotificationName:kUpdateUserInfoSuccessed object:self];
            
            // 回到上一个界面
            [self backAction];
        }
        else
        {
            // 什么都不做
        }

    }
    
    
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
    }

    if (indexPath.section == 0)
    {
        switch (indexPath.row)
        {
            case 0:
            {
                static NSString *avatarCellIdentifier = @"avatarCell";
                [tableView registerClass:[MyHomeTableViewCell class] forCellReuseIdentifier:avatarCellIdentifier];
                MyHomeTableViewCell *userAvatarCell = [tableView dequeueReusableCellWithIdentifier:avatarCellIdentifier];
                userAvatarCell.avatarImageView.image = self.userInfoModel.figureurl_qq_2;
                self.avatarImageView = userAvatarCell.avatarImageView;
                return userAvatarCell;
                break;
            }
            case 1:
                cell.textLabel.text = @"昵称";
                cell.detailTextLabel.text = self.userInfoModel.nickname;
                break;
            default:
                break;
        }
        
    }
    else
    {
        switch (indexPath.row)
        {
            case 0:
                cell.textLabel.text = @"所在地";
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%@,%@",self.userInfoModel.province,self.userInfoModel.city];
                break;
            case 1:
                cell.textLabel.text = @"一句话简介";
                break;
            default:
                break;
        }
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:14];
    return cell;
    
}

#pragma mark - 点击cell触发方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取消选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
        {
            // 弹出对话框
            UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"选取照片", nil];
            [actionSheet showFromBarButtonItem:UIBarButtonItemStylePlain animated:YES];
        }
        else if (indexPath.row == 1)
        {
            NameViewController *nameVc = [[NameViewController alloc] init];
            nameVc.userName = self.userInfoModel.nickname; // 传值
            nameVc.delegate = self; // 设置代理
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:nameVc];
            nav.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
            [self presentViewController:nav animated:YES completion:nil];
        }
    }
    else
    {
        switch (indexPath.row)
        {
            case 0:
            {
                // 调用所在地方法
                [self location];
                break;
            }
            case 1:
            {
                // 跳转到一句话简介
                IntroductionViewController *introductionVc = [[IntroductionViewController alloc] init];
                introductionVc.userIntroduction = self.userInfoModel.indirect;  // 传值
                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:introductionVc];
                nav.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                
                // 执行block代码块
                __block UserInfoTableViewController *userBlack = self;
                introductionVc.introductionBloak = ^(NSString *introduction){
                    // 进行复制
                    userBlack.userInfoModel.indirect = introduction;
                };
            
                [self presentViewController:nav animated:YES completion:nil];
                break;
            }
            default:
                break;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
        {
            return 100;
        }
    }
    
    return 40;
}


#pragma mark - 所在地
- (void)location
{
    UIView *shadowView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    shadowView.alpha = 0.05;
    shadowView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:shadowView];
    self.shadowView = shadowView;
    
    // picker
    UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(10, kScreenHeight / 2.5, kScreenWidth - 20, kScreenHeight - (kScreenHeight / 2.5) - 10)];
    pickerView.backgroundColor = [UIColor whiteColor];
    pickerView.delegate = self;
    pickerView.dataSource = self;
    pickerView.layer.cornerRadius = 3;
    pickerView.layer.masksToBounds = YES;
    [self.view addSubview:pickerView];
    self.pickerView = pickerView;
    
    // 取消
    CGRect cancelFrame = CGRectMake(pickerView.x, pickerView.y + pickerView.height + 10, pickerView.width / 2 - 0.5, 30);
    UIButton *cancelBtn = [UIButton buttonWithFrame:cancelFrame title:@"取消" backgroundColor:[UIColor whiteColor]];
    [cancelBtn addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancelBtn];
    self.cancelBtn = cancelBtn;
    
    
    // 确定
    CGRect confirmBtnFrame = CGRectMake(cancelBtn.x + cancelBtn.width + 1, pickerView.y + pickerView.height + 10, pickerView.width / 2 - 0.5, 30);
    UIButton *confirmBtn = [UIButton buttonWithFrame:confirmBtnFrame title:@"确定" backgroundColor:[UIColor whiteColor]];
    [confirmBtn addTarget:self action:@selector(confirmAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:confirmBtn];
    self.confirmBtn = confirmBtn;


}

#pragma mark - 取消按钮
- (void)cancelAction
{
    [self.shadowView removeFromSuperview]; // 从移除父视图
    [self.pickerView removeFromSuperview];
    [self.cancelBtn removeFromSuperview];
    [self.confirmBtn removeFromSuperview];
}

#pragma mark - 确定按钮
- (void)confirmAction
{
    [self.shadowView removeFromSuperview]; // 从移除父视图
    [self.pickerView removeFromSuperview];
    [self.cancelBtn removeFromSuperview];
    [self.confirmBtn removeFromSuperview];
    
    // 如果没有触发pickerView 就给一个默认值
    if (_locationString == nil)
    {
        self.locationString = @"北京 北京";
        // 分割字符串
        NSArray *locationArray = [self.locationString componentsSeparatedByString:@" "];
        self.userInfoModel.city = locationArray[1];
        self.userInfoModel.province = locationArray[0];
    }
    
    // 分割字符串
    NSArray *locationArray = [self.locationString componentsSeparatedByString:@" "];
    self.userInfoModel.city = locationArray[1];
    self.userInfoModel.province = locationArray[0];
    
    // 刷新表格
    [self.tableView reloadData];
}

#pragma mark - pickerView delegate

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    if (component == 0) {
        NSDictionary *dict = [_cityDataArray objectAtIndex:row];
        NSString *province = [dict objectForKey:@"province"];
        
        UILabel *thisLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
        thisLabel.text = province;
        return thisLabel;
    } else {
        NSDictionary *dict = [_cityDataArray objectAtIndex:[pickerView selectedRowInComponent:0]];
        NSArray *city = [dict objectForKey:@"city"];
        
        UILabel *thisLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
        thisLabel.text = [city objectAtIndex:row];
        return thisLabel;
    }
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        return [_cityDataArray count];
    } else {
        NSInteger row = [pickerView selectedRowInComponent:0];
        NSDictionary *dict = [_cityDataArray objectAtIndex:row];
        NSArray *city = [dict objectForKey:@"city"];        
        return [city count];
    }
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

#pragma mark - 选择当前的数据
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {
        [pickerView reloadComponent:1];
        [pickerView selectRow:0 inComponent:1 animated:NO];
    }
    
    NSDictionary *dict = [_cityDataArray objectAtIndex:[pickerView selectedRowInComponent:0]];
    NSString *province = [dict objectForKey:@"province"];
    NSArray *city = [dict objectForKey:@"city"];
    
    // 获取当前的选中的所在地
    
    self.locationString = [NSString stringWithFormat:@"%@ %@",province, [city objectAtIndex:[pickerView selectedRowInComponent:1]]];
//    YAXLog(@"%@", _locationString);
    

}

#pragma mark - 实现弹出对话框代理方法
#pragma 点击头像弹出对话框
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
//            NSLog(@"拍照");
            // 如果有系统相机
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                UIImagePickerController * picker = [[UIImagePickerController alloc]init];
                picker.delegate = self;
                picker.allowsEditing = YES;
                //摄像头
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:picker animated:YES completion:nil];
            }
            //如果没有系统相机提示用户
            else
            {
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"您的设备没有摄像头" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
            }
            break;
        case 1:
//            NSLog(@"选取照片");
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                UIImagePickerController * picker = [[UIImagePickerController alloc]init];
                picker.delegate = self;
                picker.allowsEditing = YES;//是否可以编辑
                //打开相册选择照片
                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                // 模态进入相册
                [self presentViewController:picker animated:YES completion:nil];

            }
            break;
        case 2:
//            NSLog(@"取消");
            
            break;
        default:
            break;
    }
}

#pragma mark - 拍摄完成后或者选择相册完成后自动调用的方法 -
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    // 获取图片
    [self.avatarImageView setImage:[info objectForKey:UIImagePickerControllerOriginalImage]];
    // 设置头像为原型
    self.avatarImageView.image = [UIImage compressImageWith:self.avatarImageView.image width:320 height:480];
    self.userInfoModel.figureurl_qq_2 = self.avatarImageView.image;
    // 模态返回
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

#pragma mark - 实现用户昵称的代理方法
- (void)updateUserName:(NSString *)userName
{
    self.userInfoModel.nickname = userName;
    [self.tableView reloadData];
}

#pragma mark - 内容警告触发方法
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    [[SDImageCache sharedImageCache] clearMemory];
}



@end
